package com.itboye.ihomebank.activity.keytwo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.itboye.ihomebank.KeyFragment;
import com.itboye.ihomebank.MainActivity;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.me.ActivityMyData;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.KeysBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.ttKey.DaoMaster;
import com.itboye.ihomebank.ttKey.DaoSession;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.ttKey.Key;
import com.itboye.ihomebank.ttKey.KeyDao;
import com.itboye.ihomebank.ttKey.MyPreference;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.MyGongJv;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.itboye.ihomebank.util.controller.LoginController;
import com.itboye.ihomebank.web.WebActivity;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.callback.visible.UnlockCallback;
import com.sitri.sdk.model.ID;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;

import org.greenrobot.greendao.database.Database;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.ihomebank.util.MyGongJv.setButtonFocusChanged;
import static com.itboye.ihomebank.util.SPUtils.get;
import static com.ttlock.bl.sdk.util.GsonUtil.gson;
import static java.lang.Long.parseLong;

/**
 * 白马门锁-普通用户
 */
public class KeyPuTongActivity extends BaseOtherActivity  implements CommonCallback,Observer {
    View v_statusbar;
    ImageView key_finish;// 返回
    TextView key_title;// 标题
    ImageView key_shezhi;// 设置
    ImageButton icon;// 开锁
    LinearLayout bottom2;
    TextView shijain_start,shijain_end;//开始时间，结束时间
    TextView key_tv_mess, key_tv_jiaozu, key_tv_weixiu, key_tv_zhangdan;//消息，交租，维修，账单
    ImageView key_img_mess, key_img_jiaozu, key_img_weixiu, key_img_zhangdan;//消息，交租，维修，账单消息显示
    private Key localKey;
    String uid;
    KeyTwoPresenter keyPresenter;

    PopupWindow popupWindow;

    String cy_mac="";
    private List<KeysBean> kensBean;//钥匙列表数据
    private List<Key> keys;//本地缓存的钥匙
    public static DaoSession daoSession;
    public static KeyDao keyDao;

    String activity="";//是从哪条转过来的，钥匙界面，还是从主界面跳转过来的常用锁

    ToggleButton key_tb;//声音开关
    String key_play="";
    @Override
    protected int layout_id() {
        return R.layout.activity_pu_tong_key;
    }

    @Override
    protected void onInitController() {
    }

    @Override
    protected void onInit() {
        keyPresenter=new KeyTwoPresenter(this);
        SLock.getServices().setIsDebug(true);
        SLock.getServices().setCommonCallback(this);
        setButtonFocusChanged(icon);

        uid = get(this, null, SPContants.USER_ID, "") + "";
        activity=getIntent().getStringExtra("activity");
        cy_mac= (String) SPUtils.get(MyApplcation.ctx, null, SPContants.CHANGYONG_MAC, "");
        key_play= (String) SPUtils.get(MyApplcation.ctx, null, SPContants.KEY_PLAY, "");
        if (key_play.equals("1")){
            key_tb.setChecked(false);
        }else {
            key_tb.setChecked(true);
        }
        setStatusBarHeight(v_statusbar);
        if (activity.equals("one")){//判断是从锁列表跳转过来的，还是常用锁
            localKey = KeyFragment.curKeys;
            key_title.setText(localKey.getLockAlias());
            String start= String.valueOf(localKey.getStartDate());
            String end= String.valueOf(localKey.getEndDate());
            if (start!=null&&end!=null){
                if (start.equals("0")){
                    bottom2.setVisibility(View.INVISIBLE);
                }else{
                    bottom2.setVisibility(View.VISIBLE);
                    shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                    shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                }
            }
        }else{
            initGreenDao();
            SLock.getServices().login(uid, "itboye");
            kensBean=new ArrayList<>();
            keys=new ArrayList<>();
            showProgressDialog("正在获取钥匙......",false);
            keyPresenter.onMyKey(uid,"");
        }
        //登录的广播
        IntentFilter filter2 = new IntentFilter("changeavart");
        registerReceiver(loginReceiver, filter2);
        //登录的广播
        IntentFilter filter1 = new IntentFilter(ActivityMyData.AVARTACTION);
        registerReceiver(loginReceivers, filter1);
    }
    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            finish();
        };
    };
    BroadcastReceiver loginReceivers = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            finish();
        };
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(loginReceiver);
        unregisterReceiver(loginReceivers);
    }
    /**
     * 数据库初始化
     */
    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "zhujias.db", null);
        Database db = helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
        keyDao = daoSession.getKeyDao();
    }
    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.key_tb:
                if (key_tb.isChecked()) {
                    ByAlert.alert("开门音开启");
                    SPUtils.put(this, null, SPContants.KEY_PLAY, "");//是否播放开锁提示音
                } else {
                    ByAlert.alert("开门音关闭");
                    SPUtils.put(this, null, SPContants.KEY_PLAY, "1");
                }
                break;
            case R.id.key_finish:
                finish();
                break;
            case R.id.key_shezhi:
                PuPoWindow(v);
                break;
            case R.id.icon://开门
                if (localKey==null){
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                icon.setBackgroundResource(R.drawable.login_logo);
                showProgressDialog("正在开门,请稍后......", true);
                SLock.getServices().unLock(localKey.getLockMac(), uid, new UnlockCallback() {
                    @Override
                    public void onBatteryChange(String mac, final int battery) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (localKey.getBattery()!=battery){
                                    keyPresenter.onSetPower(uid,localKey.getLockId(),battery);
                                }
                            }
                        });
                    }
                });
                break;

            case R.id.key_tv_mess://消息
                if (activity.equals("one")){//从锁界面跳转过来，直接返回，跳转到消息界面
                    intent = new Intent();
                    setResult(110, intent);
                    finish();
                }else{//处于锁模式，直接跳转到主界面
                    intent = new Intent(this, MainActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                }
                break;
            case R.id.key_tv_jiaozu://交租
                LoginController.onMySignClick(this, null);
                break;
            case R.id.key_tv_weixiu://维修
                LoginController.onMyHousekeeper(this, null);
                break;
            case R.id.key_tv_zhangdan://账单
                intent = new Intent(this, WebActivity.class);
                intent.putExtra(
                        "url", NetPublicConstant.WEB_URL02
                                + "/wallet/index?uid="
                                + uid + "&psw=" + (SPUtils.get(this, null, SPContants.PASSWORD, "") + ""));
                intent.putExtra("title", "资金交易明细");
                startActivity(intent);
                break;
            case R.id.set_shezhi://设置
                popupWindow.dismiss();
                intent = new Intent(this, KeySetUpActivity.class);
                intent.putExtra("lockid", localKey.getLockId());
                intent.putExtra("lockAlias", localKey.getLockAlias());
                startActivity(intent);
                break;
            case R.id.set_putong://普通模式
                popupWindow.dismiss();
                ByAlert.alert("设置成功");
                SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                break;
            case R.id.set_mensuo://门锁模式
                popupWindow.dismiss();
                intent = new Intent(this, KeyXuanZeActivity.class);
                startActivityForResult(intent,103);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==103&&resultCode==105){
            String macs=  data.getStringExtra("mac");
            String types=  data.getStringExtra("type");
            SPUtils.put(MyApplcation.ctx, null,SPContants.CHANGYONG_MAC, macs);//锁名称
            SPUtils.put(MyApplcation.ctx, null,SPContants.CHANGYONG_TYPE, types);//锁类型
            ByAlert.alert("设置成功");
        }
    }

    @Override
    public void onSuccess(final ResultData resultData) {
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (resultData.getId() == ID.UNLOCK) {
                    ByAlert.alert("门开了");
                    icon.setBackgroundResource(R.drawable.menkaile);

                    key_play= (String) SPUtils.get(MyApplcation.ctx, null, SPContants.KEY_PLAY, "");
                    if (!key_play.equals("1")){
                        MyGongJv.plays("sss.mp3");
                    }
                }
            }
        });
    }

    @Override
    public void onFailed(ResultError resultError) {
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        log(resultError.getId(), false, resultError.getErrorCode().toLog());
    }
    private void log(final ID id, final boolean isSuccess, final String log) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isSuccess) {
                    ByAlert.alert(id.name() + ":第2个");
                } else {
                    ByAlert.alert(TostKey.getStamp(log));
                }
            }
        });

    }
    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (!entity.getCode().equals(0)) {
                if (entity.getEventType() == KeyTwoPresenter.setPower_success) {
                } else if (entity.getEventType() == KeyTwoPresenter.setPower_fail) {
                }else if (entity.getEventType() == KeyTwoPresenter.myKey_success) {//我的钥匙列表
                    kensBean = (List<KeysBean>) entity.getData();
                    if (kensBean != null) {
                        if (kensBean.size() > 0) {
                            keys.clear();
                            //清空本地并重新保存数据
                            DbService.deleteAllKey();
                            for (int i = 0; i < kensBean.size(); i++) {
                                Key key = new Key();
                                key.setAccessToken(MyPreference.getStr(mContext,
                                        MyPreference.ACCESS_TOKEN));
                                if (kensBean.get(i).getType().equals("0")) {
                                    key.setAdmin(true);
                                } else {
                                    key.setAdmin(false);
                                }
                             //   key.setLockVersion(gson.toJson(kensBean.get(i).getLock_version()));
                                key.setLockName(kensBean.get(i).getLock_name());
                                key.setLockMac(kensBean.get(i).getLock_mac());
                                key.setAdminPs(kensBean.get(i).getAdminPwd());
                                key.setUnlockKey(kensBean.get(i).getLock_key());
                                key.setAdminKeyboardPwd(kensBean.get(i).getNoKeyPwd());
                                key.setDeletePwd(kensBean.get(i).getDeletePwd());
                                key.setPwdInfo("");
                                key.setTimestamp(0);
                                key.setAesKeystr(kensBean.get(i).getAesKeyStr());
                                // key.setTimezoneRawOffset(TimeZone.getDefault().getOffset(currentTimeMillis()));
                                key.setTimezoneRawOffset(Integer.parseInt(get(this, null, SPContants.SHIQU, "") + ""));

                                //上面是开锁用到的必要数据，下面这些是一些操作数据
                                key.setLockId(kensBean.get(i).getLock_id());
                                key.setKeyId(kensBean.get(i).getKey_id());
                                key.setLockAlias(kensBean.get(i).getLock_alias());
                                key.setStartDate(parseLong(kensBean.get(i).getStart()));
                                key.setEndDate(parseLong(kensBean.get(i).getEnd()));

                                key.setUser_type(kensBean.get(i).getUser_type());
                                key.setStatus(kensBean.get(i).getStatus());
                                key.setPush(kensBean.get(i).getPush());
                                key.setHouse_no(kensBean.get(i).getHouse_no());
                                key.setTypes(kensBean.get(i).getType());
                                key.setKeyStatus(kensBean.get(i).getKeyStatus());
                                key.setBattery(kensBean.get(i).getPower());
                                key.setLock_type(kensBean.get(i).getLock_type());
                                key.setHas_valid_rent(kensBean.get(i).getHas_valid_rent());
                                key.setId(keyDao.insert(key));
                                keys.add(key);

                            }
                            //清空本地并重新保存数据
                            DbService.saveKeyList(keys);

                            boolean cunzai=true;//用来判断保存的常用锁名字是否数据中也有，如果没有了。就删除掉
                            for (int i = 0; i < keys.size(); i++) {
                                if (keys.get(i).getLockMac().equals(cy_mac)){
                                    localKey = keys.get(i);
                                    key_title.setText(localKey.getTypes()+localKey.getLockAlias());
                                    String start= String.valueOf(localKey.getStartDate());
                                    String end= String.valueOf(localKey.getEndDate());
                                    if (start!=null&&end!=null){
                                        if (start.equals("0")){
                                            bottom2.setVisibility(View.INVISIBLE);
                                        }else{
                                            bottom2.setVisibility(View.VISIBLE);
                                            shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                                            shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                                        }
                                    }
                                }
                                cunzai =keys.get(i).getLockMac().contains(cy_mac);
                            }
                            if (localKey==null){
                                ByAlert.alert("保存的锁不存在了");
                                SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                                SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                                Intent intent=new Intent(KeyPuTongActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            }else{//锁存在的时候   判断异常吗，然后直接跳转到主界面吧
                                String type=localKey.getTypes();
                                if (type.equals("110402")||type.equals("110405")||type.equals("110408")||type.equals("110410")) {
                                    ByAlert.alert("该钥匙处于异常状态");
                                    SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                                    SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                                    Intent intent=new Intent(KeyPuTongActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        }
                        else{
                            ByAlert.alert("保存的锁不存在了");
                            SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                            SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                            Intent intent=new Intent(KeyPuTongActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                } else if (entity.getEventType() == KeyTwoPresenter.myKey_fail) {
                    ByAlert.alert(entity.getData());
                }
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }
    /**
     * 钥匙搜索切换框
     */
    private void PuPoWindow(View v) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.item_shezhi, null);
        TextView set_shezhi = (TextView) view
                .findViewById(R.id.set_shezhi);
        TextView set_putong = (TextView) view
                .findViewById(R.id.set_putong);
        TextView set_mensuo = (TextView) view
                .findViewById(R.id.set_mensuo);

        set_shezhi.setOnClickListener(this);
        set_putong.setOnClickListener(this);
        set_mensuo.setOnClickListener(this);
        popupWindow = new PopupWindow(view, FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAsDropDown(v);
    }
}
